﻿# region Using System
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Runtime.InteropServices;//捕捉错误
# endregion

# region Using ArcGIS
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.esriSystem;//不用从引用加入
using ESRI.ArcGIS.Carto;//管理图层
using ESRI.ArcGIS.CartoUI;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
# endregion

namespace popGis.LJP
{
    class myFeatureClass
    {
    //    //存在的删除,不存在的创建
    //    private void InitFeatureClasses(IWorkspace wks,string fcName)
    //    {
    //            IFeatureClass pFeatureClass;
    //            //pFeatureClass = Utility.getFeatureClassByName(fcName, wks);
    //            
    //            if (pFeatureClass != null)
    //            {
    //                //删除要素类
    //                IDataset dataSet = pFeatureClass as IDataset;
    //                dataSet.CanDelete();
    //                dataSet.Delete();
    //            }
    //            IFeatureClass fc = CreateFeatClass(wks, fcName);
    //    }

        /// <summary>
        /// 创建 IFeatureClass
        /// </summary>
        /// <returns></returns>
       //private IFeatureClass CreateFeatClass(IWorkspace wks, string fcName)
       // {
       //     IFeatureWorkspace pFwks = wks as IFeatureWorkspace;
       //     IFeatureClass pFeatClass = null;
       //     try
       //     {
       //         //定义该FeatureClass中的字段集
       //         //添加者两句代码是自动生成FeatureClass的OBJECTID字段和SHAPE字段，以便下面修改ＳＨＡＰＥ几何类型
       //         IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
       //         IObjectClassDescription objDesc = fcDesc as IObjectClassDescription;

       //         IFields pFields = objDesc.RequiredFields;
       //         IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

       //         //定义具体字段
       //         IField pField = null;
       //         IFieldEdit pFieldEdit = null;

       //         //几何类型字段修改
       //         pField = pFields.get_Field(1);
       //         //pFieldEdit = this.getShapeFieldEdit(pField, "自定义的一个枚举类型");

       //         //要素类普通字段的定义
       //         for (int i = 0; i < tableDef.FieldCount; i++)
       //         {
       //             pField = new FieldClass();
       //             pFieldEdit = pField as IFieldEdit;
       //             pFieldsEdit.AddField(this.getCommonField(pField, pFieldEdit, tableDef, i));//循环提供的一个对象“tableDef”的属性字段，赋值给该ＦｅａｔｕｒｅＣｌａｓｓ
       //         }

       //         pFeatClass = pFwks.CreateFeatureClass(fcName, pFields, null, null, esriFeatureType.esriFTSimple, pFields.get_Field(1).Name, "");
       //     }
       //     catch (Exception ex)
       //     {
       //         MessageBox.Show(ex.Message);
       //     }
       //     return pFeatClass;
       // }

    /// <summary>
    /// 编辑几何类型字段
    /// </summary>
    /// <param name="pField">该要素的Shape字段</param>
    /// <param name="geoType">该要素类的几何类型（自定义的枚举类型）</param>
    /// <returns></returns>
    //    private IFieldEdit getShapeFieldEdit(IField pField, VCTGeometryType geoType)
    //    {
    //        IFieldEdit pFieldEdit = pField as IFieldEdit;

    //        IGeometryDef pGeoDef = null;
    //        IGeometryDefEdit pGeoDefEdit = null;
    //        pGeoDef = new GeometryDefClass();
    //        pGeoDefEdit = pGeoDef as IGeometryDefEdit;

    //        switch (geoType)
    //        {
    //            case VCTGeometryType.vctGeometryPoint:
    //                pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
    //                break;
    //            case VCTGeometryType.vctGeometryLine:
    //                pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
    //                break;
    //            case VCTGeometryType.vctGeometryPolygon:
    //                pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
    //                break;
    //            case VCTGeometryType.vctGeometryAnnontation:
    //                pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
    //                break;
    //            default:
    //                pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryAny;
    //                break;
    //        }
    //        pGeoDefEdit.SpatialReference_2 = this.CreateSpatialRefence("Xian 1980 3 Degree GK Zone 40.prj");

    //        pFieldEdit.GeometryDef_2 = pGeoDefEdit;

    //        return pFieldEdit;
    //    }

    /// <summary>
    /// 空间参考的定义
    /// </summary>
    /// <param name="prjName">空间参考文件名称，带后缀名</param>
    /// <returns></returns>
    //    private ISpatialReference CreateSpatialRefence(string prjName)
    //    {
    //        ISpatialReference psr = null;
    //        try
    //        {
    //            string prjPath = Application.StartupPath + "\\" + prjName;
    //            ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
    //            psr = pSRF.CreateESRISpatialReferenceFromPRJFile(prjPath);

    //            //psr.SetDomain(vctDocument.FileHead.MinX, vctDocument.FileHead.MaxX, vctDocument.FileHead.MinY, vctDocument.FileHead.MaxY);
    //            ISpatialReferenceResolution psrRes = psr as ISpatialReferenceResolution;
    //            psrRes.set_XYResolution(true, 0.00001);
    //        }
    //        catch (Exception ex)
    //        {
    //            MessageBox.Show("空间参考文件出错！" + ex.Message);
    //        }
    //        return psr;
    //    }

     //<summary>
     //设置要素类中普通字段
     //</summary>
     //<param name="pField">要素类的普通字段</param>
     //<param name="pFieldEdit">字段的编辑</param>
     //<param name="tableDef">存放字段的对象</param>
     //<returns></returns>
     //   //private IField getCommonField(IField pField, IFieldEdit pFieldEdit, VCTTableDef tableDef, int i)
     //   {
     //       pFieldEdit.Name_2 = tableDef.Fields[i].Name;
     //       //字段类型定义
     //       VCTFieldType fieldType = tableDef.Fields[i].Type;

     //       switch (fieldType)
     //       {
     //           case VCTFieldType.vctFieldChar:
     //           case VCTFieldType.vctFieldVarchar:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
     //               break;
     //           case VCTFieldType.vctFieldInteger:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
     //               break;
     //           case VCTFieldType.vctFieldFloat:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
     //               pFieldEdit.Precision_2 = tableDef.Fields[i].precision;
     //               break;
     //           case VCTFieldType.vctFieldBoolean:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeSmallInteger;
     //               tableDef.Fields[i].Type.ToString();
     //               break;
     //           case VCTFieldType.vctFieldDate:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDate;
     //               break;
     //           case VCTFieldType.vctFieldTime:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDate;
     //               break;
     //           case VCTFieldType.vctFieldVarbin:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
     //               break;
     //           default:
     //               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
     //               break;
     //       }
     //       pFieldEdit.Length_2 = tableDef.Fields[i].width;

     //       return pField;
     //   }


    //ITable的操作
    //创建、删除ITable对象


    /// <summary>
    /// 添加头文件Table并添加头文件记录
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="wks"></param>
    //    //private void saveMETADATA(string tableName, IWorkspace wks)
    //    //{
    //    //    try
    //    //    {
    //    //        ITable pTable = VCT2LanduseUtils.getTableByName(tableName, wks);

    //    //        if (pTable != null)
    //    //        {
    //    //          //如果存在该表，删除
    //    //            IDataset dataSet;
    //    //            dataSet = pTable as IDataset;
    //    //            dataSet.CanDelete();
    //    //            dataSet.Delete();
    //    //        }

    //    //        pTable = createTableByAO(tableName, wks);
                
    //    //        if (pTable!=null)
    //    //        {
    //    //            insertRecordByAO(pTable);
    //    //        }
    //    //    }
    //    //    catch (Exception ex)
    //    //    {
    //    //        System.Diagnostics.Debug.Print(ex.Message);
    //    //        MessageBox.Show("头文件表操作出现异常！");
    //    //    }
    //    //}

    /// 根据Table的名字，在工作空间中获取该ITable对象
    //    public static ITable getTableByName(string tblName, IWorkspace wks)
    //    {
    //        ITable pTable = null;
    //        try
    //        {
    //            if (wks.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
    //            {
    //                IDatabaseConnectionInfo coninf = wks as IDatabaseConnectionInfo;
    //                tblName = coninf.ConnectedUser + "." + tblName;
    //                if (coninf.ConnectedDatabase != null && (!coninf.ConnectedDatabase.Equals("")))
    //                {
    //                    tblName = coninf.ConnectedDatabase + "." + tblName;
    //                }
    //            }
    //            if ((wks as IWorkspace2).get_NameExists(esriDatasetType.esriDTTable, tblName))
    //            {
    //                pTable = (wks as IFeatureWorkspace).OpenTable(tblName);
    //            }
    //        }
    //        catch (Exception ex)
    //        {
    //            System.Diagnostics.Debug.Print(ex.Message);
    //        }

    //        return pTable;

    //    }

    /// <summary>
    /// AO 方式创建头文件信息表
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="wks"></param>
    /// <returns></returns>
    //    private ITable createTableByAO(string tableName, IWorkspace wks)
    //    {
    //        IFeatureWorkspace featWks = wks as IFeatureWorkspace;
            
    //        ESRI.ArcGIS.esriSystem.UID uid = new ESRI.ArcGIS.esriSystem.UIDClass();
    //        ITable pTable;
    //        IFields pFields;
    //        IFieldsEdit pFieldsEdit;

    //        uid.Value = "esriGeoDatabase.Object";
    //        #region 表字段结构定义
    //        pFields = new FieldsClass();
    //        pFieldsEdit = pFields as IFieldsEdit;

    //        IField pField;
    //        IFieldEdit pFieldEdit;
    //        pField = new FieldClass();
    //        pFieldEdit = pField as IFieldEdit;
            
    //        //OID字段定义，如果没有该字段，那么就不能通过table.CreateRow来创建行，需要通过table.insert(true)，返回ICursor来创建
    //        pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;

    //        pFieldsEdit.AddField(pField);

    //        pField = new FieldClass();
    //        pFieldEdit = pField as IFieldEdit;
    //        pFieldEdit.Name_2 = "ProjectParam";
    //        pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
    //        pFieldEdit.Editable_2 = true;
    //        pFieldEdit.Length_2 = 50;

    //        pFieldsEdit.AddField(pField);

    //       //。。。。。。。字段的定义。。。。。。。。。
    //        #endregion

    //        IFieldChecker fieldChecker = new FieldCheckerClass();
    //        IEnumFieldError enumFieldError = null;
    //        IFields validateFields = null;
    //        fieldChecker.ValidateWorkspace = wks;
    //        fieldChecker.Validate(pFields, out enumFieldError, out validateFields);

    //        pTable = featWks.CreateTable(tableName, validateFields, uid, null, "");

    //        return pTable;
    //    }

    /// <summary>
    /// AO方式向头文件Table中插入一条记录
    /// </summary>
    /// <param name="pTable"></param>
    //    //private void insertRecordByAO(ITable pTable)
    //    //{
    //    //    IRow row = pTable.CreateRow();
    //    //    int ppIndex = row.Fields.FindField("ProjectParam");
    //    //      //。。。。。。。字段索引的获取。。。。。。。。。
    //    //    int yMaxIndex = row.Fields.FindField("YMAX");

    //    //    row.set_Value(ppIndex, vctDocument.FileHead.Projection);
    //    //     //。。。。。。。给字段赋值。。。。。。。。。
    //    //    row.set_Value(yMaxIndex, vctDocument.FileHead.MaxY);

    //    //    row.Store();
    //    //}


    }

    class CreateFeatureClass
    {

        //----------------------------TO DO :-------------
        //------------------------创建FeatureClass-----------------------
        /// <summary>
        /// 创建有外表关联关系的要素集对象
        /// </summary>
        /// <param name="featureClassName"></param>
        /// <returns></returns>
        //public IFeatureClass getFeatureClass(/*IFields pFields,*/ string featureClassName)
        //{
        //    IFeatureClass thisFeatureCls = null; bool exist = false;

        //    thisFeatureCls = getFeatureClassByName(featureClassName, pWorkspace,out exist);//除旧迎新
        //    if (thisFeatureCls != null && exist)
        //    {
        //        //删除要素类
        //        IDataset dataSet = thisFeatureCls as IDataset;
        //        dataSet.CanDelete();
        //        dataSet.Delete();
        //    }

        //    thisFeatureCls = CreateFeatureClass(pWorkspace, featureClassName, (ITable)pDisplayTable.DisplayTable);

        //    Marshal.ReleaseComObject(pWorkspace);

        //    return thisFeatureCls;
        //}
        /// <summary>
        /// 创建要素集 - 貌似只含字段不含具体数据
        /// </summary>
        /// <param name="wks"></param>
        /// <param name="fcName"></param>
        /// <param name="pTable"></param>
        /// <returns></returns>
        //public IFeatureClass CreateFeatureClass(IWorkspace wks, string fcName,ITable pTable)
        //{
        //    IFeatureWorkspace pFwks = wks as IFeatureWorkspace;
        //    IFeatureClass pFeatClass = null;
        //     try
        //     {
        //         //定义该FeatureClass中的字段集
        //         //添加者两句代码是自动生成FeatureClass的OBJECTID字段和SHAPE字段，以便下面修改ＳＨＡＰＥ几何类型
        //         IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass();
        //         IObjectClassDescription objDesc = fcDesc as IObjectClassDescription;

        //         IFields pFields = objDesc.RequiredFields;
        //         IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

        //         //定义具体字段
        //         IField pField = null;
        //         IFieldEdit pFieldEdit = null;

        //         //1、几何类型字段修改
        //         pField = pFields.get_Field(1);
        //         pFieldEdit = getShapeFieldEdit(pField,"Polygon");

        //         //2、要素类普通字段的定义
        //         int fieldCount = pDisplayTable.DisplayTable.Fields.FieldCount;//外表字段总数
        //         int startposition = pDisplayTable.DisplayTable.FindField("SHAPE_Area");//外表字段起始 前 位置
        //         for (int i = startposition + 1; i < fieldCount; i++)
        //         {
        //             pField = new FieldClass();
        //             pField = pTable.Fields.get_Field(i);//获得外表字段
        //             pFieldEdit = pField as IFieldEdit;
        //             pFieldEdit.Name_2 = DataConvertion.getValidFeatureClassName(pField.Name);//将字段名中的 . 替换成 _
        //             pFieldEdit.Type_2 = pField.Type;

        //             pFieldsEdit.AddField(pField);
        //         }
        //         //3、创建新的要素类（只有字段啊）
        //         pFeatClass = pFwks.CreateFeatureClass(fcName, pFields, null, null, esriFeatureType.esriFTSimple, pFields.get_Field(1).Name, "");
        //     }
        //     catch (Exception ex)
        //     {
        //         MessageBox.Show(ex.Message, "Error from Create_FeatureClass()");
        //     }
        //    return pFeatClass;
        //}

        /// <summary>
        /// 编辑几何类型字段
        /// </summary>
        /// <param name="pField">该要素的Shape字段</param>
        /// <param name="geoType">该要素类的几何类型 [Point/Line/Polygon/Annontation]</param>
        /// <returns></returns>
        public IFieldEdit getShapeFieldEdit(IField pField, string geoType)
        {
            IFieldEdit pFieldEdit = pField as IFieldEdit;
            //----begin：编辑几何性质
            IGeometryDef pGeoDef = null;
            IGeometryDefEdit pGeoDefEdit = null;
            pGeoDef = new GeometryDefClass();
            pGeoDefEdit = pGeoDef as IGeometryDefEdit;
            //几何类型
            switch (geoType)
            {
                case "Point":
                    pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                    break;
                case "Line":
                    pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                    break;
                case "Polygon":
                    pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                    break;
                case "Annontation":
                    pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                    break;
                default:
                    pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryAny;
                    break;
            }
            pGeoDefEdit.SpatialReference_2 = getWGS84SpatialRef();// using wgs84 SpatialReference
            //----end：结束编辑几何属性

            pFieldEdit.GeometryDef_2 = pGeoDefEdit;
            return pFieldEdit;
        }

        /// <summary>
        /// 按名称获取工作空间里的要素集
        /// </summary>
        /// <param name="fcname"></param>
        /// <param name="wks"></param>
        /// <returns></returns>
        public IFeatureClass getFeatureClassByName(string fcname, IWorkspace wks, out bool exist)
        {
            IFeatureWorkspace pFWS = wks as IFeatureWorkspace;
            IFeatureClass pfc = null;
            try
            {
                pfc = pFWS.OpenFeatureClass(fcname);
                exist = true;
            }
            catch
            {
                exist = false;
            }
            return pfc;
        }

        /// <summary>
        /// 获得WGS84坐标系
        /// </summary>
        /// <returns></returns>
        public ISpatialReference getWGS84SpatialRef()
        {
            Type factoryType = Type.GetTypeFromProgID("esriGeometry.SpatialReferenceEnvironment");
            System.Object obj = Activator.CreateInstance(factoryType);
            ISpatialReferenceFactory3 spatialReferenceFactory =
                obj as ISpatialReferenceFactory3;

            ISpatialReference spatialReference =
                spatialReferenceFactory.CreateSpatialReference((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

            ISpatialReferenceInfo spatialReferenceInfo =
                spatialReference as ISpatialReferenceInfo;

            //System.Windows.Forms.MessageBox.Show(spatialReferenceInfo.Abbreviation);
            //System.Windows.Forms.MessageBox.Show(spatialReferenceInfo.Alias);
            //System.Windows.Forms.MessageBox.Show(spatialReferenceInfo.FactoryCode.ToString());
            //System.Windows.Forms.MessageBox.Show(spatialReferenceInfo.Name);
            //System.Windows.Forms.MessageBox.Show(spatialReferenceInfo.Remarks);

            return spatialReference;
        }
    }

}
